<template>
  <div class="app-container">
    <table width="100%" height="900px" border="1" align="center" cellpadding="1" cellspacing="1" class="table-form-1">
      <!--项目绩效目标-->
      <tr>
        <th>项目名称</th>
        <td>{{ obj.name ? obj.name : '' }}</td>
        <th>续存状态</th>
        <td>{{ showDictLabel('BudgetProjectViability', obj.viability) }}</td>
        <th>项目属性</th>
        <td colspan="3">{{ showDictLabel('BudgetProjectAttribute', obj.attribute) }}</td>
      </tr>
      <tr>
        <th>项目起止时间</th>
        <th>开始年度</th>
        <td colspan="2">{{ obj.startTime ? obj.startTime : '' }}</td>
        <th>终止年度</th>
        <td colspan="3">{{ obj.endTime ? obj.endTime : '' }}</td>
      </tr>
      <tr>
        <th>项目预算（元）</th>
        <th>申请财政金额</th>
        <td>￥{{ obj.totalFund ? obj.totalFund : 0 }}</td>
        <th>社会投入资金</th>
        <td>￥{{ obj.putinFund ? obj.putinFund : 0 }}</td>
        <th>当年资金</th>
        <td colspan="3">￥{{ obj.putinFund ? obj.putinFund : 0 }}</td>
      </tr>
      <tr>
        <th>用款单位</th>
        <td colspan="3">{{ showIdLabel(governmentList, obj.useGovId, 'governmentName') }}</td>
        <th>申报单位</th>
        <td colspan="3">{{ showIdLabel(governmentList, obj.applyGovId, 'governmentName') }}</td>
      </tr>
      <tr>
        <th>主管部门</th>
        <td>{{ showIdLabel(budgetCompetentList, obj.managerOrgId, 'name') }}</td>
        <th>主管部门联系人</th>
        <td>{{ showIdLabel(budgetCompetentList, obj.managerOrgId, 'contact') }}</td>
        <th>主管部门联系电话</th>
        <td colspan="3">{{ showIdLabel(budgetCompetentList, obj.managerOrgId, 'telephone') }}</td>
      </tr>
      <tr>
        <th>项目实施单位</th>
        <td>{{ showIdLabel(governmentList, obj.workGovId, "governmentName") }}</td>
        <th>项目负责人</th>
        <td>{{ showIdLabel(userList, obj.workUserId, 'name') }}</td>
        <th>项目负责联系电话</th>
        <td colspan="3">{{ obj.workUserContact ? obj.workUserContact : '' }}</td>
      </tr>
      <tr>
        <th>上一年项目预算安排情况</th>
        <td colspan="7">{{ obj.previousArrange ? obj.previousArrange : '' }}</td>
      </tr>
      <tr>
        <th>项目内容（概况）</th>
        <td colspan="7">{{ obj.summarize ? obj.summarize : '' }}</td>
      </tr>
      <tr>
        <th>设立依据及申报理由</th>
        <td colspan="7">{{ obj.reason ? obj.reason : '' }}</td>
      </tr>
      <tr>
        <th rowspan="3">项目绩效目标</th>
        <th colspan="3">总目标</th>
        <th colspan="4">本年度目标</th>
      </tr>
      <tr style="padding: .3125rem !important;">
        <!-- contenteditable="true" -->
        <td colspan="3" rowspan="2" class="td-content">{{ obj.targetAll ? obj.targetAll : '' }}</td>
        <td colspan="4" rowspan="2">{{ obj.targetCurrent ? obj.targetCurrent : '' }}</td>
      </tr>
      <tr></tr>
      <!--本年度绩效指标-->
      <!--本年度绩效指标-->
      <tr>
        <th :rowspan="parseInt(rowHeadCurrentNum + 1)" width="6%">本年度绩效指标</th>
        <th width="10%">一级指标</th>
        <th width="12%">二级指标</th>
        <th width="12%">三级指标</th>
        <th width="25%">指标内容</th>
        <th width="8%">指标周期值</th>
        <th width="10%">年度指标值</th>
        <th>备注</th>
      </tr>
      <template v-if="kpiListCurrent.length > 0">
        <tr>
          <td :rowspan="kpiListCurrent[0].rowspan">{{ kpiListCurrent[0].kpiName }}</td>
          <td :rowspan="kpiListCurrent[0].children[0].children.length ? kpiListCurrent[0].children[0].children.length : 1" v-if="kpiListCurrent[0].children.length > 0">{{ kpiListCurrent[0].children[0].kpiName }}</td>
          <td v-else></td>
          <template v-if=" kpiListCurrent[0].children.length > 0">
            <td>{{ kpiListCurrent[0].children[0].children.length > 0 ? kpiListCurrent[0].children[0].children[0].kpiName : '' }}</td>
            <td>{{ kpiListCurrent[0].children[0].children.length > 0 ? kpiListCurrent[0].children[0].children[0].kpiContent : ''}}</td>
            <td>{{ kpiListCurrent[0].children[0].children.length > 0 ? kpiListCurrent[0].children[0].children[0].kpiValue : '' }}</td>
            <td>{{ kpiListCurrent[0].children[0].children.length > 0 ? kpiListCurrent[0].children[0].children[0].kpiValuePeriod : '' }}</td>
            <td>{{ kpiListCurrent[0].children[0].children.length > 0 ? kpiListCurrent[0].children[0].children[0].remark : '' }}</td>
          </template>
          <template v-else>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </template>
        </tr>
        <template v-if="kpiListCurrent[0].children.length > 0">
          <template v-for="(item,index) in kpiListCurrent[0].children[0].children" :key="index">
            <tr v-if="index > 0">
              <td>{{ item.kpiName }}</td>
              <td>{{ item.kpiContent }}</td>
              <td>{{ item.kpiValuePeriod }}</td>
              <td>{{ item.kpiValue }}</td>
              <td>{{ item.remark }}</td>
            </tr>
          </template>
        </template>
        <!--第一个一级指标剩余二级指标-->
        <template v-for="(item,index) in kpiListCurrent[0].children" :key="index">
          <template v-if="index > 0">
            <template v-if="item.children.length > 0">
              <tr v-for="(item1,index1) in item.children" :key="index1">
                <td :rowspan="item.children.length ? item.children.length : 1">{{ item.kpiName }}</td>
                <td>{{ item1.kpiName }}</td>
                <td>{{ item1.kpiContent }}</td>
                <td>{{ item1.kpiValuePeriod }}</td>
                <td>{{ item1.kpiValue }}</td>
                <td>{{ item1.remark }}</td>
              </tr>
            </template>
            <template v-else>
              <tr>
                <td :rowspan="item.children.length ? item.children.length : 1">{{ item.kpiName }}</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
              </tr>
            </template>
          </template>
        </template>
        <!--剩余一级指标所有指标展示-->
        <template v-for="(item,index) in kpiListCurrent" :key="index">
            <template v-if="index > 0">
              <template v-if="item.children.length > 0">
                <template v-for="(item1,index1) in item.children" :key="index1">
                  <template v-if="item1.children.length > 0">
                    <tr v-for="(item2,index2) in item1.children" :key="index2" >
                      <td :rowspan="item.rowspan" v-if="index1 == 0 && index2 == 0">{{ item.kpiName }}</td>
                      <td :rowspan="index2 == item1.children.length  || index2 == 0 ? item1.children.length : 1" v-if="index2 == item1.children.length  || index2 == 0">{{ item1.kpiName }}</td>
                      <td>{{ item2.kpiName ? item2.kpiName : '' }}</td>
                      <td>{{ item2.kpiContent ? item2.kpiContent : '' }}</td>
                      <td>{{ item2.kpiValuePeriod ? item2.kpiValuePeriod : '' }}</td>
                      <td>{{ item2.kpiValue ? item2.kpiValue : '' }}</td>
                      <td>{{ item2.remark ? item2.remark : '' }}</td>
                    </tr>
                  </template>
                  <tr v-else>
                    <td :rowspan="item.rowspan" v-if="index1 == 0">{{ item.kpiName }}</td>
                    <td :rowspan="1">{{ item1.kpiName }}</td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                  </tr>
                </template>
              </template>
              <template v-else>
                <tr>
                  <td :rowspan="item.children.length ? item.children.length : 1">{{ item.kpiName }}</td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
              </template>
            </template>
        </template>
      </template>
    </table>
  </div>
</template>

<script setup>
import {ref, watch} from 'vue'
import {doGet} from "@/config/http";
import {svc, showIdLabel, getListPageSize, showDictLabel} from "@/config/common";
import initListStore from '@/store/modules/initList'

let obj = ref({
  projectTwoId: null, // 二级项目ID
  name: null, // 项目名称
  viability: null, // 存续状态
  source: null, // 项目来源
  attribute: null, // 项目属性(新增项目、持续项目、跨年度项目)
  totalFund: 0, // 申请财政总额
  putinFund: 0, // 社会投入资金
  currFund: 0, // 当年资金
  useGovId: null, //用款单位ID
  applyGovId: null, //申报单位ID
  previousArrange: '', //上一年项目预算安排情况
  managerOrgId: null, // 主管部门ID
  managerName: null, // 主管部门联系人
  managerUserContact: null, // 主管部门联系电话
  workGovId: null, // 项目实施单位ID
  workUserId: null, // 项目负责人ID
  workUserContact: null, // 项目负责人联系方式
  state: null, // 状态(0保存、1提交审批、2审批通过、3审批驳回、4撤回)
  startTime: '', // 起始年度
  endTime: '', // 终止年度
  summarize: '',//项目概述
  reason: '', //设立依据及申报理由
  isDebenture: '',//是否债券可用项目
  isScientific: '', // 是否科研项目
  isConstruction: '', // 是否基建项目
  constructionDesc: '', // 基建立项情况
  isAgent: '', // 是否代建项目
  agentGovId: null, //代建单位ID
  isGovernmentPurchase: false, // 是否政府采购
  purchaseProject: null, // 采购项目
  purchaseKind: null, // 采购品目
  purchaseRequire: null, // 采购需求概况
  purchaseDate: null, // 预计采购时间
  purchaseAttr: null, // 资金性质
  purchaseFund: 0, // 采购金额
  purchasePrice: 0, // 单价
  purchaseNum: 0, // 采购数量
  purchaseUnit: null, // 计量单位
  targetAll: null, // 项目绩效总目标
  targetCurrent: null, // 项目绩效本年度目标
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
  approveId: null,
})

const props = defineProps({
  budgetNewId: {
    required: true,
    type: String,
  },
})

let purchases = ref([])
let items = ref([])
let years = ref([])
let kpiListCurrent = ref([])
let rowHeadCurrentNum = ref(0)
let governmentList = initListStore().governmentList
// let organizationList = ref([])
let userList = initListStore().userList
let budgetCompetentList = initListStore().budgetCompetentList

const getData = async id => {
  // 这里调用接口
  obj.value = await doGet(svc, '/budget-new/' + id, {}, true)
  let p1 = doGet(svc, '/budget-new-purchase/listByField', {field: 'budgetNewId', values: id}, false)
  let p2 = doGet(svc, '/budget-new-item/listByField', {field: 'budgetNewId', values: id}, false)
  let p3 = doGet(svc, '/budget-new-year/listByField', {field: 'budgetNewId', values: id}, false)
  let p4 = doGet(svc, '/budget-new-kpi/listByField', {field: 'budgetNewId', values: id, sortField: 'weight',sortType: 'asc'}, false)
  let resArray = await Promise.all([p1, p2, p3, p4])
  purchases.value = resArray[0]
  items.value = resArray[1]
  years.value = resArray[2]
  kpiListCurrent.value = kpisCompose(resArray[3].filter(item => item.performanceType === '1'))
  rowHeadCurrentNum.value = getKpiLonglen(kpiListCurrent.value)
  obj.value.totalFund = 0
  items.value.map(item => {
    obj.value.totalFund += parseFloat(item.price) * parseFloat(item.num)
  })
}

// async function initList() {
//   let p1 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false)
//   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
//   let p3 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
//   let p4 = doGet(svc, '/budget-competent/page', {pageSize: getListPageSize()}, false)
//   let resArray = await Promise.all([p1, p2, p3, p4])
//   governmentList.value = resArray[0]['records']
//   organizationList.value = resArray[1]['records']
//   userList.value = resArray[2]['records']
//   budgetCompetentList.value = resArray[3]['records']
// }

watch(() => props.budgetNewId, async val => {
  await getData(val)
  await initList()
},{immediate:true})

function kpisCompose(list, pid) {
  return list
  .filter((item) =>
    !pid ? item.parentId === null : item.parentId === pid
  )
  .map(item => {
    item.children = kpisCompose(list, item.id);
    if (item.children && item.children.length > 0){
      let num2 = 0
      let num3 = 0
      if (item.level === 1) {
        num2 += item.children.length ? item.children.length : 1
        item.children.forEach(item1 => {
          num3 += item1.children.length ? item1.children.length : 1
        })
      }
      item.rowspan = num2 > num3 ? num2 : num3
    }
    return item;
  });
}

// 计算本年度指标表格行数
let num1  = 0
let num3 = 0
function getKpiLonglen(list) {
  let num2 = 0
  list.forEach(item => {
    if (item.level === 1) {
      num2 += item.children.length ? item.children.length : 1
      if (!item.children.length) {
        num1 += 1
      }
    } else if (item.level === 2) {
      num3 += item.children.length ? item.children.length : 1
    }
    getKpiLonglen(item.children)
  });
  return num2 > num3 ? num2 : num3 + num1
}
</script>
<style scoped>
.table-form, .table-form-1 {
  border-collapse: collapse;
  text-align:center;
}
td {
  padding: 20px 0;
}
</style>
